package com.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.mall.dto.*;
import com.mall.entity.*;
import com.mall.mapper.*;
import com.mall.service.PmsProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品信息 服务实现类
 * </p>
 *
 * @author zzx
 * @since 2022-06-15
 */
@Service
public class PmsProductServiceImpl extends ServiceImpl<PmsProductMapper, PmsProduct> implements PmsProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PmsProductServiceImpl.class);
    @Autowired
    private PmsMemberPriceMapper memberPriceMapper;
    @Autowired
    private PmsProductLadderMapper productLadderMapper;
    @Autowired
    private PmsProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;
    @Autowired
    private CmsSubjectProductRelationMapper subjectProductRelationMapper;
    @Autowired
    private CmsPrefrenceAreaProductRelationMapper prefrenceAreaProductRelationMapper;
    @Autowired
    private PmsProductVertifyRecordMapper productVertifyRecordMapper;
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private PmsProductMapper productMapper;

    @Override
    public int create(PmsProductParam productParam) {
        int count;
        //创建商品
        PmsProduct product = productParam;
        product.setId(null);
        save(product);
        //根据促销类型设置价格：会员价格、阶梯价格、满减价格
        Long productId = product.getId();
        //会员价格
        relateAndInsertList(memberPriceMapper, productParam.getMemberPriceList(), productId);
        //阶梯价格
        relateAndInsertList(productLadderMapper, productParam.getProductLadderList(), productId);
        //满减价格
        relateAndInsertList(productFullReductionMapper, productParam.getProductFullReductionList(), productId);
        //处理sku的编码
        handleSkuStockCode(productParam.getSkuStockList(), productId);
        //添加sku库存信息
        relateAndInsertList(skuStockMapper, productParam.getSkuStockList(), productId);
        //添加商品参数,添加自定义商品规格
        relateAndInsertList(productAttributeValueMapper, productParam.getProductAttributeValueList(), productId);
        //关联专题
        relateAndInsertList(subjectProductRelationMapper, productParam.getSubjectProductRelationList(), productId);
        //关联优选
        relateAndInsertList(prefrenceAreaProductRelationMapper, productParam.getPrefrenceAreaProductRelationList(), productId);
        count = 1;
        return count;
    }


    @Override
    public PmsProductResult getUpdateInfo(Long id) {
        return productMapper.getUpdateInfo(id);
    }

    @Override
    public int update(Long id, PmsProductParam productParam) {
        int count;
        //更新商品信息
        PmsProduct product = productParam;
        product.setId(id);
        updateById(product);
        //会员价格
        QueryWrapper<PmsMemberPrice> deleteMemberPriceWrapper = new QueryWrapper();
        deleteMemberPriceWrapper.eq("product_id", id);
        memberPriceMapper.delete(deleteMemberPriceWrapper);
        relateAndInsertList(memberPriceMapper, productParam.getMemberPriceList(), id);
        //阶梯价格
        QueryWrapper<PmsProductLadder> deleteLadderWrapper = new QueryWrapper();
        deleteLadderWrapper.eq("product_id", id);
        productLadderMapper.delete(deleteLadderWrapper);
        relateAndInsertList(productLadderMapper, productParam.getProductLadderList(), id);
        //满减价格
        QueryWrapper<PmsProductFullReduction> deleteFullReductionWrapper = new QueryWrapper();
        deleteFullReductionWrapper.eq("product_id", id);
        productFullReductionMapper.delete(deleteFullReductionWrapper);
        relateAndInsertList(productFullReductionMapper, productParam.getProductFullReductionList(), id);
        //修改sku库存信息
        handleUpdateSkuStockList(id, productParam);
        //修改商品参数,添加自定义商品规格
        QueryWrapper<PmsProductAttributeValue> deleteProductAttributeValueWrapper = new QueryWrapper();
        deleteProductAttributeValueWrapper.eq("product_id", id);
        productAttributeValueMapper.delete(deleteProductAttributeValueWrapper);
        relateAndInsertList(productAttributeValueMapper, productParam.getProductAttributeValueList(), id);
        //关联专题
        QueryWrapper<CmsSubjectProductRelation> deleteSubjectProductRelationWrapper = new QueryWrapper();
        deleteSubjectProductRelationWrapper.eq("product_id", id);
        subjectProductRelationMapper.delete(deleteSubjectProductRelationWrapper);
        relateAndInsertList(subjectProductRelationMapper, productParam.getSubjectProductRelationList(), id);
        //关联优选
        QueryWrapper<CmsPrefrenceAreaProductRelation> deletePrefrenceAreaProductRelationWrapper = new QueryWrapper();
        deletePrefrenceAreaProductRelationWrapper.eq("product_id", id);
        prefrenceAreaProductRelationMapper.delete(deletePrefrenceAreaProductRelationWrapper);
        relateAndInsertList(prefrenceAreaProductRelationMapper, productParam.getPrefrenceAreaProductRelationList(), id);
        count = 1;
        return count;
    }

    @Override
    public List<PmsProduct> list(PmsProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        return productMapper.getList(productQueryParam);
    }

    @Override
    public int updateVerifyStatus(List<Long> ids, Integer verifyStatus, String detail) {
        int count = update(new UpdateWrapper<PmsProduct>().in("id", ids).set("status", verifyStatus)) ? 1 : 0;
        List<PmsProductVertifyRecord> list = new ArrayList<>();
        //修改完审核状态后插入审核记录
        for (Long id : ids) {
            PmsProductVertifyRecord record = new PmsProductVertifyRecord();
            record.setProductId(id);
            record.setDetail(detail);
            record.setStatus(verifyStatus);
            record.setVertifyMan("test");
            list.add(record);
        }
        ExecutorService executorService = Executors.newFixedThreadPool(list.size());
        for (PmsProductVertifyRecord record : list) {
            executorService.execute(() -> {
                productVertifyRecordMapper.insert(record);
            });
        }
        try {
            executorService.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            LOGGER.error("线程异常", e);
        }
        executorService.shutdown();

        return count;
    }

    @Override
    public int updatePublishStatus(List<Long> ids, Integer publishStatus) {
        return update(new UpdateWrapper<PmsProduct>().in("id", ids).set("publish_status", publishStatus)) ? 1 : 0;
    }

    @Override
    public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
        return update(new UpdateWrapper<PmsProduct>().in("id", ids).set("recommend_status", recommendStatus)) ? 1 : 0;
    }

    @Override
    public int updateNewStatus(List<Long> ids, Integer newStatus) {
        return update(new UpdateWrapper<PmsProduct>().in("id", ids).set("new_status", newStatus)) ? 1 : 0;
    }

    @Override
    public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
        return update(new UpdateWrapper<PmsProduct>().in("id", ids).set("delete_status", deleteStatus)) ? 1 : 0;
    }

    @Override
    public List<PmsProduct> list(String keyword) {
        QueryWrapper<PmsProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_status", 0);
        if (!keyword.isEmpty()) {
            queryWrapper.like("name", keyword).or().eq("delete_status", 0).like("product_sn", keyword);
        }
        return list(queryWrapper);
    }


    /**
     * 建立和插入关系表操作
     *
     * @param mapper    可以操作的mapper
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object mapper, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = mapper.getClass().getMethod("insertList", List.class);
            insertList.invoke(mapper, dataList);
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }


    private void handleUpdateSkuStockList(Long id, PmsProductParam productParam) {
        //当前的sku信息
        List<PmsSkuStock> currSkuList = productParam.getSkuStockList();
        //当前没有sku直接删除
        if (CollUtil.isEmpty(currSkuList)) {
            QueryWrapper<PmsSkuStock> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("product_id", id);
            skuStockMapper.delete(queryWrapper);
            return;
        }
        //否则对sku进行相应操作

        //获取初始sku信息
        QueryWrapper<PmsSkuStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", id);
        skuStockMapper.delete(queryWrapper);
        List<PmsSkuStock> oriStuList = skuStockMapper.selectList(queryWrapper);

        //获取新增sku信息
        List<PmsSkuStock> insertSkuList = currSkuList.stream().filter(item -> item.getId() == null).collect(Collectors.toList());
        //获取需要更新的sku信息
        List<PmsSkuStock> updateSkuList = currSkuList.stream().filter(item -> item.getId() != null).collect(Collectors.toList());
        List<Long> updateSkuIds = updateSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
        //获取需要删除的sku信息
        List<PmsSkuStock> removeSkuList = oriStuList.stream().filter(item -> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
        handleSkuStockCode(insertSkuList, id);
        handleSkuStockCode(updateSkuList, id);
        //新增sku
        if (CollUtil.isNotEmpty(insertSkuList)) {
            relateAndInsertList(skuStockMapper, insertSkuList, id);
        }
        //删除sku
        if (CollUtil.isNotEmpty(removeSkuList)) {
            List<Long> removeSkuIds = removeSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
            QueryWrapper deleteWrapper = new QueryWrapper();
            deleteWrapper.in("id", removeSkuIds);
            skuStockMapper.delete(deleteWrapper);
        }
        //修改sku
        if (CollUtil.isNotEmpty(updateSkuList)) {
            for (PmsSkuStock pmsSkuStock : updateSkuList) {
                skuStockMapper.updateById(pmsSkuStock);
            }
        }

    }

    private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
        if (CollectionUtils.isEmpty(skuStockList)) return;
        for (int i = 0; i < skuStockList.size(); i++) {
            PmsSkuStock skuStock = skuStockList.get(i);
            if (skuStock.getSkuCode().isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i + 1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }


    @Override
    public List<FrontIndexProductDto> getHome(List<Long> ids, Long brandId, String productCategoryName, Integer pageSize, Integer pageNum) {
        List<FrontIndexProductDto> result = new ArrayList<>();
        QueryWrapper<PmsProduct> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("delete_status", 0);
        productQueryWrapper.eq("publish_status", 1);
        productQueryWrapper.eq("recommend_status", 1);
        String parentName = null;

        if (ids != null && !ids.isEmpty()) {
            productQueryWrapper.in("id", ids);
        }
        if (brandId != null && brandId > 0) {
            productQueryWrapper.eq("brand_id", brandId);
        }
        if (productCategoryName != null && !productCategoryName.isEmpty()) {
            List<PmsProductCategory> productCategoryList = productCategoryMapper.selectList(new QueryWrapper<>());
            //找出productCategoryList中的名称与productCategoryName相同的项
            PmsProductCategory productCategory = productCategoryList.stream().filter(item -> item.getName().equals(productCategoryName)).findFirst().orElse(null);
            if (productCategory != null) {
                if (productCategory.getLevel() == 0) {
                    //说明传入为父类
                    parentName = productCategoryName;
                    //找出productCategoryList中的parentId等于productCategory的id的项的id
                    List<Long> parentIds = productCategoryList.stream().filter(item -> item.getParentId().equals(productCategory.getId())).map(PmsProductCategory::getId).collect(Collectors.toList());
                    productQueryWrapper.in("product_category_id", parentIds);
                } else {
                    //说明传入为子类
                    //parentName等于productCategoryList中的id等于productCategory.getParentId的项的name
                    parentName = productCategoryList.stream().filter(item -> item.getId().equals(productCategory.getParentId())).findFirst().orElse(null).getName();
                    productQueryWrapper.eq("product_category_name", productCategoryName);
                }
            }
        }
        List<PmsProduct> productList = productMapper.selectList(productQueryWrapper);
        PageHelper.startPage(pageNum, pageSize);
        String finalParentName = parentName;
        result = productList.stream().map(item -> {
            FrontIndexProductDto frontIndexProductDto = new FrontIndexProductDto();
            frontIndexProductDto.setProduct(item);
            frontIndexProductDto.setProductCategoryParentName(finalParentName);
            return frontIndexProductDto;
        }).collect(Collectors.toList());
        return result;
    }

    @Override
    public int createComment(Long id, Long memberId, String content, int star) {
        //生成一个时间戳yyyy-MM-dd HH:mm:ss
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return productMapper.createComment(id, memberId, content, star, sdf.format(new Date()));
    }

    @Override
    public FrontProductDetailDto showProduct(Long id) {
        FrontProductDetailDto result = new FrontProductDetailDto();
        if (id != null && id > 0) {
            PmsProduct product = productMapper.selectById(id);
            if (product != null) {
                result.setProduct(product);
                List<FrontCateAttributeDto> cateAttributeList = productMapper.getFrontCateAttributeList(product.getProductAttributeCategoryId());
                result.setFrontCateAttributeDto(cateAttributeList);
                List<PmsSkuStock> skuStockList = skuStockMapper.selectList(new QueryWrapper<PmsSkuStock>().eq("product_id", id));
                result.setStockList(skuStockList);
                List<FrontCommentDto> commentList = productMapper.getFrontCommentList(product.getId());
                result.setFrontCommentDtoList(commentList);
            }
        }
        return result;
    }

    @Override
    public List<PmsProduct> getListByIds(List<Long> ids) {
        return productMapper.selectBatchIds(ids);
    }

}
